package com.request;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class Sql2Json implements SqlToJson{
	
	static int i = 0;
	public Sql2Json() {
		super();
	}
	/**
	 * this function transfoms a result set into a json object
	 * @param rs
	 * @return
	 * @throws JSONException
	 */
	public JSONObject responseObject(ResultSet rs) throws JSONException{
		JSONObject jsonO=new JSONObject();
		try{
			ResultSetMetaData meta=rs.getMetaData();
			int columnCount=meta.getColumnCount();
			rs.next();
			//every column will be put in the JSON
			for(int i=0;i<columnCount;i++){
				String label = meta.getColumnLabel(i+1);
				String value = rs.getString(i+1);
				jsonO.put(label,value);
			}
		}
		catch(Exception e){
			System.err.println("SelectTable : "+e.getMessage());
		}
		i++;
		return jsonO;
	}
	/**
	 * this function transfoms a result set into a json array
	 * @param rs
	 * @return
	 * @throws JSONException
	 */
	public JSONArray responseArray(ResultSet rs) throws JSONException{
		JSONArray jsonA=new JSONArray();
		try{
			//first get the count of records in the resultset
			rs.last();
			int rowCount=rs.getRow();
			rs.beforeFirst();
			// then, while there's a record, transforms it into a json object and put it in a jason array
			for(int i=0;i<rowCount;i++){
				jsonA.put(this.responseObject(rs));
			}
		}
		catch(Exception e){
			System.err.println("SelectTable : "+e.getMessage());
		}
		return jsonA;
	}
}
